#!/usr/bin/python
# -*- coding: ISO-8859-1 -*-
import SocketServer,sys,re
from ConfigParser import ConfigParser

Config = ConfigParser()
Config.read('nerdp2p.conf')
PeerList = []
PeerListOnServer = []
MaxPeersOnServer=int(Config.get('server','max_peers_on_server'));
class NerdRequestHandler(SocketServer.BaseRequestHandler):
	global PeerList
	global PeerListOnServer
	global Config
	global MaxPeersOnServer
	print 'MaxPeersOnServer: ' + str(MaxPeersOnServer) + '\n'
	def server_bind(self):
		SocketServer.ThreadingTCPServer.server_bind(self)
		self.socket.setdefaulttimeout(2)
		self.run = True

	def setup(self):
		print self.client_address, 'Conectou' 
		
	def handle(self):
		#try:
			while 1:
				data = self.request.recv(1024)
				#Quit
				if data.strip() == 'QUIT':
					return
				#Start Video
				elif data.strip() == 'START':
					return
				#Stop video
				elif data.strip() == 'STOP':
					return
				#Register to tracker
				elif data.strip() == 'REGISTER':
					#Coloco o peer na lista de peers
					if PeerList.count(self.client_address) <= 0:
						PeerList.append(self.client_address)
						#Se tem espaco na lista de peers on server, coloco o peer lá
						if len(PeerListOnServer) < MaxPeersOnServer :
							if PeerListOnServer.count(self.client_address) == 0 :
								PeerListOnServer.append(self.client_address)
						self.request.send('OK');
					else:
						self.request.send('ERR');
				#Remove from tracker
				elif data.strip() == 'REMOVE':
					if PeerList.count(self.client_address) > 0:
						PeerList.remove(self.client_address)
						if PeerListOnServer.count(self.client_address) > 0:
							PeerListOnServer.remove(self.client_address)
							print 'Removido ' + str(self.client_address) + ' da lista de peers no server'
						self.request.send('OK');
					else:
						self.request.send('ERR');
				#List peers
				elif data.strip() == 'LIST':
						#O peer so pode listar se estiver registrado
						if PeerList.count(self.client_address) >0:
							#Se for pra pegar so server, manda SERVER, senão manda lista de peers
							if PeerListOnServer.count(self.client_address) > 0 :
								self.request.send('SERVER')
							else:
								for Ip in PeerList:
									self.request.send(str(Ip[0])+'\n')
							self.request.send('OK');
						else:
							self.request.send('ERR');
				else:
					self.request.send('ERR')
			#except:
			#	print "Nao pude enviar \n"
			#	return
	def finish(self):
		if PeerListOnServer.count(self.client_address) > 0:
			PeerListOnServer.remove(self.client_address)
			print 'Removido ' + str(self.client_address) + ' da lista de peers no server'
		if PeerList.count(self.client_address) > 0:
			PeerList.remove(self.client_address)
			print 'Removido ' + str(self.client_address) + ' da lista de peers'
		print str(self.client_address), 'Desconectou'
		self.request.send('OK')

#server host is a tuple ('host', port)
SocketServer.ThreadingTCPServer.allow_reuse_address = 1
Server_Port = int(Config.get('server','Server_Port'))
print 'Server escutando na porta: ' + str(Server_Port) 
server = SocketServer.ThreadingTCPServer(('',Server_Port), NerdRequestHandler)

try:
	server.serve_forever()
except KeyboardInterrupt:
	sys.exit(0)


